<template>
  <div class="report-container">
    <el-card class="header-card" shadow="hover">
      <div class="header">
        <h1>就业成熟度评估报告</h1>
        <div class="header-actions">
          <el-button type="primary" @click="exportToPdf" :loading="exporting">
            <el-icon><Download /></el-icon>
            导出PDF
          </el-button>
          <el-button type="success" @click="printReport">
            <el-icon><Printer /></el-icon>
            打印报告
          </el-button>
          <el-button @click="startNewAssessment">
            <el-icon><Refresh /></el-icon>
            重新评估
          </el-button>
        </div>
      </div>
    </el-card>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <div v-else-if="error" class="error-container">
      <el-alert
        title="加载失败"
        description="无法加载评估报告，请稍后重试"
        type="error"
        show-icon
      />
      <el-button @click="loadReport">重新加载</el-button>
    </div>

    <div v-else-if="report" class="report-content" ref="reportContent">
      <el-card class="report-header-card" shadow="hover">
        <div class="report-header">
          <h2>大学生就业成熟度评估报告</h2>
          <p class="report-date">{{ currentDate }}</p>
        </div>
      </el-card>

      <el-card class="summary-section" shadow="hover">
        <h3>整体评估</h3>
        <div class="score-overview">
          <el-statistic
            v-model="overallScore"
            :precision="1"
            title="综合评分"
            suffix="/5"
            :value-style="{ fontSize: '48px', color: getScoreColor(overallScore) }"
          />
          <div class="score-description">
            <el-descriptions border>
              <el-descriptions-item label="评估等级">
                <el-tag :type="getScoreTagType(overallScore)">{{ getScoreLevel(overallScore) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="评估说明" :span="2">
                {{ getScoreDescription(overallScore) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-card>

      <el-card class="dimensions-section" shadow="hover">
        <h3>维度评分可视化</h3>
        <div class="charts-container">
          <div class="chart-item">
            <h4>维度雷达图</h4>
            <div ref="radarChart" style="height: 400px; width: 100%" />
          </div>
          <div class="chart-item">
            <h4>维度对比柱状图</h4>
            <div ref="barChart" style="height: 400px; width: 100%" />
          </div>
        </div>
        
        <div class="dimension-details">
          <h4>详细评分</h4>
          <el-table :data="dimensionScores" style="width: 100%">
            <el-table-column prop="name" label="评估维度" width="180" />
            <el-table-column prop="score" label="评分" width="120">
              <template #default="{ row }">
                <el-rate v-model="row.score" :disabled="true" />
              </template>
            </el-table-column>
            <el-table-column prop="score" label="进度条" width="180">
              <template #default="{ row }">
                <el-progress :percentage="row.score * 20" :color="getScoreColor(row.score)" />
              </template>
            </el-table-column>
            <el-table-column prop="feedback" label="反馈建议">
              <template #default="{ row }">
                <el-tag :type="getScoreTagType(row.score)" effect="plain">{{ getDimensionFeedback(row.name, row.score) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <el-card class="report-body-card" shadow="hover">
        <h3>评估报告详情</h3>
        <div class="report-body" v-html="parsedReport"></div>
      </el-card>
    </div>

    <div v-else class="no-report">
      <el-alert
        title="未找到报告"
        description="没有找到该对话的评估报告"
        type="warning"
        show-icon
      />
      <el-button @click="router.push('/')">返回首页</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import MarkdownIt from 'markdown-it';
import html2pdf from 'html2pdf.js';
import { ElButton, ElAlert, ElSkeleton, ElCard, ElStatistic, ElDescriptions, ElDescriptionsItem, ElTag, ElTable, ElTableColumn, ElRate, ElProgress, ElMessage } from 'element-plus';
import { Printer, Refresh, Download } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
// 移除不存在的useLoading导入;
import mockService from '../services/mockAssessmentService.js';

const route = useRoute();
const router = useRouter();

// 状态管理
const loading = ref(true);
const error = ref(false);
const report = ref(null);
const exporting = ref(false);
const reportContent = ref(null);
const radarChart = ref(null);
const barChart = ref(null);
let radarChartInstance = null;
let barChartInstance = null;
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true
});

// 解析的报告HTML
const parsedReport = computed(() => {
  if (!report.value) return '';
  return md.render(report.value);
});

// 当前日期
const currentDate = computed(() => {
  const now = new Date();
  return now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
});

// 模拟维度评分数据（实际应该从报告中提取）
const dimensionScores = ref([
  { name: '职业认知', score: 0, feedback: '' },
  { name: '专业能力', score: 0, feedback: '' },
  { name: '通用技能', score: 0, feedback: '' },
  { name: '求职准备', score: 0, feedback: '' },
  { name: '职业素养', score: 0, feedback: '' },
  { name: '心理准备', score: 0, feedback: '' }
]);

// 综合评分
const overallScore = computed(() => {
  const total = dimensionScores.value.reduce((sum, dim) => sum + dim.score, 0);
  return Math.round(total / dimensionScores.value.length * 10) / 10;
});

// 获取评分等级描述
const getScoreDescription = (score) => {
  if (score >= 4.5) return '优秀：您的就业准备非常充分，具备很强的就业竞争力。';
  if (score >= 3.5) return '良好：您的就业准备较为充分，具有较好的就业竞争力。';
  if (score >= 2.5) return '一般：您的就业准备基本满足要求，仍有提升空间。';
  if (score >= 1.5) return '薄弱：您的就业准备相对不足，需要加强各方面能力。';
  return '不足：您的就业准备严重不足，建议系统性地提升自己。';
};

// 获取评分颜色
const getScoreColor = (score) => {
  if (score >= 4) return '#67c23a'; // 优秀 - 绿色
  if (score >= 3) return '#409eff'; // 良好 - 蓝色
  if (score >= 2) return '#e6a23c'; // 一般 - 黄色
  return '#f56c6c'; // 较差 - 红色
};

// 获取评分标签类型
const getScoreTagType = (score) => {
  if (score >= 4) return 'success';
  if (score >= 3) return 'primary';
  if (score >= 2) return 'warning';
  return 'danger';
};

// 获取评分等级
const getScoreLevel = (score) => {
  if (score >= 4.5) return '优秀';
  if (score >= 3.5) return '良好';
  if (score >= 2.5) return '一般';
  if (score >= 1.5) return '薄弱';
  return '不足';
};

// 获取维度反馈
const getDimensionFeedback = (dimensionName, score) => {
  const feedbackMap = {
    '职业认知': {
      5: '职业定位清晰，目标明确',
      4: '职业规划较为完善',
      3: '有基本职业认知',
      2: '职业认知不够深入',
      1: '缺乏职业规划'
    },
    '专业能力': {
      5: '专业知识扎实，实践能力强',
      4: '专业基础良好',
      3: '具备基本专业能力',
      2: '专业能力需要提升',
      1: '专业基础薄弱'
    },
    '通用技能': {
      5: '沟通协作等能力突出',
      4: '通用技能良好',
      3: '具备基本通用技能',
      2: '通用技能有所欠缺',
      1: '通用技能不足'
    },
    '求职准备': {
      5: '求职材料完善，面试技巧成熟',
      4: '求职准备较充分',
      3: '基本准备就绪',
      2: '求职准备不够充分',
      1: '缺乏求职准备'
    },
    '职业素养': {
      5: '职业素养高，责任感强',
      4: '职业素养良好',
      3: '具备基本职业素养',
      2: '职业素养需要培养',
      1: '职业素养不足'
    },
    '心理准备': {
      5: '心理状态成熟，抗压能力强',
      4: '心理准备充分',
      3: '具备基本心理准备',
      2: '心理准备有待加强',
      1: '心理承受能力较弱'
    }
  };
  
  const dimension = feedbackMap[dimensionName];
  if (!dimension) return '';
  
  const scoreKey = Math.max(1, Math.min(5, Math.round(score)));
  return dimension[scoreKey];
};

// 雷达图配置
const radarOption = computed(() => {
  return {
    title: {
      text: '',
    },
    tooltip: {},
    legend: {
      data: ['得分'],
      bottom: 0
    },
    radar: {
      indicator: dimensionScores.value.map(dim => ({ name: dim.name, max: 5 })),
      shape: 'circle',
      splitNumber: 5
    },
    series: [{
      name: '就业成熟度评分',
      type: 'radar',
      data: [{
        value: dimensionScores.value.map(dim => dim.score),
        name: '得分',
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.3)'
        },
        lineStyle: {
          color: '#409eff'
        },
        itemStyle: {
          color: '#409eff'
        }
      }]
    }]
  };
});

// 柱状图配置
const barOption = computed(() => {
  return {
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dimensionScores.value.map(dim => dim.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 5,
      interval: 1
    },
    series: [{
      name: '评分',
      type: 'bar',
      data: dimensionScores.value.map((dim, index) => ({
        value: dim.score,
        itemStyle: {
          color: getScoreColor(dim.score)
        }
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}/5'
      }
    }]
  };
});

// 初始化图表
const initCharts = async () => {
  await nextTick();
  
  // 初始化雷达图
  if (radarChart.value) {
    if (!radarChartInstance) {
      radarChartInstance = echarts.init(radarChart.value);
    }
    radarChartInstance.setOption(radarOption.value);
  }
  
  // 初始化柱状图
  if (barChart.value) {
    if (!barChartInstance) {
      barChartInstance = echarts.init(barChart.value);
    }
    barChartInstance.setOption(barOption.value);
  }
};

// 从报告中提取维度评分
const extractScoresFromReport = (reportText) => {
  // 为演示目的，生成随机评分
  dimensionScores.value.forEach(dim => {
    dim.score = Math.floor(Math.random() * 2) + 3; // 随机生成3-5分
    dim.feedback = getDimensionFeedback(dim.name, dim.score);
  });
  
  // 更新图表
  nextTick(() => {
    initCharts();
  });
};

// 导出PDF报告
const exportToPdf = async () => {
  if (!reportContent.value) return;
  
  exporting.value = true;
  
  try {
    const opt = {
      margin: 10,
      filename: `就业成熟度评估报告_${currentDate.value.replace(/[年月]/g, '-').replace(/日/g, '')}.pdf`,
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 2 },
      jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };
    
    // 导出报告内容
    await html2pdf().set(opt).from(reportContent.value).save();
    
    // 显示成功消息
    ElMessage.success('报告导出成功！');
  } catch (error) {
    console.error('导出PDF失败:', error);
    ElMessage.error('报告导出失败，请重试');
  } finally {
    exporting.value = false;
  }
};

// 加载报告
const loadReport = async () => {
  const conversationId = route.params.conversationId;
  if (!conversationId) {
    error.value = true;
    loading.value = false;
    return;
  }

  loading.value = true;
  error.value = false;

  try {
    let reportData;
    
    // 尝试调用后端API
    try {
      const historyResponse = await axios.get(`/api/assessment/${conversationId}`);
      reportData = historyResponse.data.report;
    } catch (apiError) {
      console.log('后端API不可用，使用Mock数据服务');
      // 使用mock数据服务
      const mockHistory = await mockService.getConversationHistory(conversationId);
      reportData = mockHistory ? mockHistory.report : null;
      
      // 如果mock数据中也没有报告，使用默认的模拟报告
      if (!reportData) {
        reportData = mockService.generateMockReport();
      }
    }

    if (reportData) {
      report.value = reportData;
      extractScoresFromReport(reportData);
    } else {
      // 如果没有报告，可能评估还未完成
      error.value = true;
    }
  } catch (err) {
    console.error('加载报告失败:', err);
    // 即使出错，也显示一个模拟报告
    report.value = mockService.generateMockReport();
    extractScoresFromReport(report.value);
    error.value = false;
  } finally {
    loading.value = false;
  }
};

// 打印报告
const printReport = () => {
  window.print();
};

// 开始新的评估
const startNewAssessment = () => {
  const newConversationId = Date.now().toString(36) + Math.random().toString(36).substr(2);
  router.push(`/assessment/${newConversationId}`);
};

// 响应式更新图表
watch(() => dimensionScores.value, () => {
  initCharts();
}, { deep: true });

// 窗口大小改变时重新调整图表大小
const handleResize = () => {
  if (radarChartInstance) {
    radarChartInstance.resize();
  }
  if (barChartInstance) {
    barChartInstance.resize();
  }
};

// 监听路由参数变化
watch(() => route.params.conversationId, () => {
  loadReport();
});

// 生命周期钩子
onMounted(() => {
  loadReport();
});
</script>

<style scoped>
.report-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.header-card {
  margin-bottom: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.header h1 {
  margin: 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.loading-container {
  margin: 40px 0;
}

.error-container, .no-report {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  gap: 24px;
}

.report-content {
  background: white;
  border-radius: 8px;
}

.report-header-card {
  margin-bottom: 24px;
}

.report-header {
  text-align: center;
  padding: 20px 0;
}

.report-header h2 {
  color: #333;
  margin-bottom: 12px;
  font-size: 24px;
  font-weight: 600;
}

.report-date {
  color: #666;
  font-size: 14px;
}

.summary-section {
  margin-bottom: 24px;
}

.summary-section h3 {
  color: #333;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: 600;
}

.score-overview {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.score-description {
  margin-top: 16px;
}

.dimensions-section {
  margin-bottom: 24px;
}

.dimensions-section h3 {
  color: #333;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: 600;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 32px;
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

.chart-item {
  background: #fafafa;
  padding: 20px;
  border-radius: 8px;
}

.chart-item h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  text-align: center;
}

.dimension-details {
  margin-top: 32px;
}

.dimension-details h4 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.report-body-card {
  margin-bottom: 24px;
}

.report-body-card h3 {
  color: #333;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: 600;
}

.report-body {
  color: #333;
  line-height: 1.8;
  font-size: 16px;
}

.report-body h3, .report-body h4 {
  color: #333;
  margin-top: 30px;
  margin-bottom: 15px;
}

.report-body p {
  margin-bottom: 15px;
  text-align: justify;
}

/* 打印样式优化 */
@media print {
  .header-actions {
    display: none;
  }
  
  .report-container {
    max-width: none;
    margin: 0;
    padding: 10px;
  }
  
  .report-content {
    border-radius: 0;
  }
  
  .el-card {
    box-shadow: none !important;
    border: 1px solid #e0e0e0;
  }
  
  .charts-container {
    break-inside: avoid;
  }
}
</style>